package com.openatc.agent.service.impl;

import com.google.gson.*;
import com.openatc.agent.model.User;
import com.openatc.agent.utils.TokenUtil;
import com.openatc.comm.data.MessageData;
import com.openatc.core.common.Constants;
import com.openatc.core.model.InnerError;
import com.openatc.core.model.RESTRet;
import com.openatc.core.util.RESTRetUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import static com.openatc.comm.common.CosntDataDefine.getresponse;
import static com.openatc.comm.common.LogUtil.SERVICE_RESPONSE_SUCCESS;
import static com.openatc.core.common.IErrorEnumImplInner.E_105;
import static com.openatc.core.common.IErrorEnumImplInner.E_301;
import static com.openatc.core.common.IErrorEnumImplOuter.E_4001;
import static com.openatc.core.common.IErrorEnumImplOuter.E_4008;

/**
 * @Classname CommService
 * @Description 抽取controller层公用的方法
 * @Date 2022/12/20 14:14
 * @Created by kedacom
 */
@Service
public class CommonService {

    @Autowired
    private CommServiceDown commServiceDown;

    private Gson gson = new GsonBuilder().create();

    /**
     * 根据查询条件中的组织机构，构建组织机构查询条件
     * @param orgCode
     * @return
     */
    public String buildOrgCondition(String orgCode) {
        User user = commServiceDown.getUserInfo();
        String user_orgCode = user.getOrganization();
        String orgCondition = "";
        if (StringUtils.hasLength(orgCode)) {
            // 管理员/查询所有组织机构("*")，不添加组织机构条件
            if (commServiceDown.isAdminRole(user.getRoleNames())) {
                if (!"*".equals(orgCode)) {
//                    orgCondition = String.format("code='%s'",orgCode);
                    orgCondition = String.format("code like '%%%s%%'",orgCode);
                }
            }
            // 非管理员
            else {
                // 用户组织机构为*
                if ("*".equals(user_orgCode)) {
//                        查询的组织机构不为"*"
                    if (!"*".equals(orgCode)) {
//                        orgCondition = String.format("code='%s'",orgCode);
                        orgCondition = String.format("code like '%%%s%%'",orgCode);
                    }
                }
                // 用户组织机构不为*
                else {
                    // 查询的组织机构为*，把用户组织机构当作条件
                    if ("*".equals(orgCode)) {
//                        orgCondition = String.format("code='%s'",user_orgCode);
                        orgCondition = String.format("code like '%%%s%%'",user_orgCode);
                    } else {
                        // 用户不属于查询条件中的组织机构，要返回空数据
                        if (!user_orgCode.equals(orgCode)){
                            // 添加一个恒假条件,保证返回空数据
                            orgCondition = "1=2";
                        }
                        // 查询条件中的组织机构和用户所属组织机构一致，再添组织机构条件
                        else {
                            orgCondition = String.format("code like '%%%s%%'",orgCode);
                        }
                    }
                }
            }
        } else {
            // 普通用户，默认把当前用户的组织机构作为条件
            if (!commServiceDown.isAdminRole(user.getRoleNames())) {
                // 如果用户的组织机构不为*，则添加组织机构条件
                if (!"*".equals(user_orgCode)) {
                    if (user_orgCode == null) {
                        orgCondition = String.format("code is NULL");
                    } else {
                        orgCondition = String.format("code like '%%%s%%'",user_orgCode);
                    }
                }
            }
        }
        return orgCondition;
    }

    /**
     * 添加where和and
     * @param whereCondition
     * @param temp
     * @return
     */
    public String addWhereCondition(String whereCondition, String temp) {
        if(whereCondition == null)
            whereCondition = "";

        if (!StringUtils.hasLength(temp)) {
            return whereCondition;
        }

        if(whereCondition.isEmpty()) {
            whereCondition = whereCondition.concat(" where ");
        }
        else{
            whereCondition = whereCondition.concat(" and ");
        }
        whereCondition = whereCondition.concat(temp);

        return  whereCondition;
    }

    /**
     * 校验请求参数
     * @param requestData
     * @param params
     */
    public void verifyParam(JsonObject requestData, String... params) {
        if (params == null || params.length == 0) {
            return;
        }
        for (String param : params) {
            JsonElement paramElement = requestData.get(param);
            if (paramElement == null) {
                throw new IllegalArgumentException(param);
            }
        }
    }

    /**
     * 是否有模糊查询过滤条件
     * @param requestData
     * @return
     */
    public boolean hasSearchCondition(JsonObject requestData) {
        return hasSpecialValue(requestData,"search") && (!"".equals(requestData.get("search").getAsString()));
    }

    /**
     * 是否存在组织机构过滤条件
     * @param requestData
     * @return
     */
    public boolean hasOrgCondition(JsonObject requestData) {
        return hasSpecialValue(requestData,"code") && (!"".equals(requestData.get("code").getAsString()));
    }

    /**
     * 是否存在指定得字段
     * @return
     */
    private boolean hasSpecialValue(JsonObject requestData,String key) {
        return requestData.get(key) != null;
    }


    /**
     * 判断消息是否发送成功
     * @param ret
     * @return
     */
    public boolean isSuccessSendMsg(RESTRet ret) {
        boolean successSendMsg = false;
        if (ret.isSuccess()) {
            MessageData res = (MessageData) ret.getData();
            if (!SERVICE_RESPONSE_SUCCESS.equals(res.getSource())) {
                successSendMsg = true;
            }
        }
        return successSendMsg;
    }


    /**
     * 给ret应答结构中添加字段
     * @param ret
     * @return
     */
    public JsonElement addPropertyForRet(RESTRet ret,String agentid) {
        // 下发消息失败
        if (!ret.isSuccess()) {
            InnerError innerError = null;
            if (ret.getData() != null) {
                innerError = (InnerError) ret.getData();
                innerError.setAgentid(agentid);
                innerError.setContent(null);
            } else {
                innerError = RESTRetUtils.innerErrorObj(agentid,E_105,null);
            }
            RESTRet requestFailed = RESTRetUtils.errorDetialObj(E_4001, innerError);
            return gson.toJsonTree(requestFailed);
        } else {
            MessageData res = (MessageData) ret.getData();
            // 信号机不在线，忽略
            if (SERVICE_RESPONSE_SUCCESS.equals(res.getSource())) {
                InnerError innerError = RESTRetUtils.innerErrorObj(agentid, E_301, null);
                RESTRet deviceOffline = RESTRetUtils.errorDetialObj(E_4008, innerError);
                return gson.toJsonTree(deviceOffline);
            }
            // 下发消息成功
            else {
                // 处理特征参数请求
                if (getresponse.equals(res.getOperation())) {
                    RESTRet success = RESTRetUtils.successObj(res);
                    return gson.toJsonTree(success);
                } else {
                    JsonObject msgStatus = new JsonObject();
                    msgStatus.addProperty("agentid", agentid);

                    RESTRet success = RESTRetUtils.successObj(msgStatus);
                    return gson.toJsonTree(success);
                }
            }
        }
    }



//    public boolean isSuccessSendMsg(JsonArray data, MessageData requestData, RESTRet ret, Map<String,RESTRet> statusMap) {
//        boolean successSendMsg = false;
//        // 下发消息失败
//        if (!ret.isSuccess()) {
//            InnerError innerError = null;
//            if (ret.getData() != null) {
//                innerError = (InnerError) ret.getData();
//                innerError.setAgentid(requestData.getAgentid());
//                innerError.setContent(null);
//            } else {
//                innerError = RESTRetUtils.innerErrorObj(requestData.getAgentid(),E_105,null);
//            }
//            RESTRet requestFailed = RESTRetUtils.errorDetialObj(E_4001, innerError);
//            data.add(gson.toJsonTree(requestFailed));
//        } else {
//            MessageData res = (MessageData) ret.getData();
//            // 信号机不在线，忽略
//            if (SERVICE_RESPONSE_SUCCESS.equals(res.getSource())) {
//                InnerError innerError = RESTRetUtils.innerErrorObj(requestData.getAgentid(), E_301, null);
//                RESTRet deviceOffline = RESTRetUtils.errorDetialObj(E_4008, innerError);
//                data.add(gson.toJsonTree(deviceOffline));
//            }
//            // 下发消息成功
//            else {
//                successSendMsg = true;
//                JsonObject msgStatus = new JsonObject();
//                msgStatus.addProperty("agentid", requestData.getAgentid());
//
//                RESTRet success = RESTRetUtils.successObj(msgStatus);
//                data.add(gson.toJsonTree(success));
//            }
//        }
//        return successSendMsg;
//    }

    private void addStatus(RESTRet ret, JsonArray data) {
        JsonElement retElement = gson.toJsonTree(ret);
        // 如果状态中已经有当前设备失败的，不再添加

        // 如果状态中

    }

    public boolean isSuccessMsgElement(JsonElement currentDevStatus) {
        RESTRet ret = gson.fromJson(currentDevStatus, RESTRet.class);
        return ret.isSuccess();
    }

    /**
     * 需要联合dev表查询的sql，可以调用该方法生成join on 语句
     * 该方法返回的sql会自动过滤出指定用户名下agentid
     * @param userName
     * @return
     */
    public String createJoinSqlByUserName(String userName, String tmpTableName) {

        String joinKey = " JOIN";
        String joinSql = String.format("( SELECT agentid,name FROM dev where " +
                "(CASE " +
                " WHEN ( SELECT userrole FROM (SELECT r.name userrole FROM t_role r JOIN t_user_role ur ON r.id = ur.role_id " +
                "      JOIN t_user u ON ur.user_id = u.id  WHERE u.user_name = '%s') as usr1 WHERE position('admin' in usr1.userrole) > 0) NOTNULL " +
                " THEN 1 = 1" +
                " WHEN (SELECT userrole FROM (SELECT r.name userrole FROM t_role r JOIN t_user_role ur  ON r.id = ur.role_id JOIN t_user u" +
                "       ON ur.user_id = u.id WHERE u.user_name = '%s') as usr1 WHERE position('superadmin' in usr1.userrole) > 0) NOTNULL" +
                " THEN 1 = 1 " +
                " WHEN (SELECT count(organization) FROM t_user WHERE user_name = '%s') = 0 or (SELECT organization FROM t_user WHERE user_name = '%s') = ''" +
                " THEN code IS NULL" +
                " WHEN (SELECT count(organization) FROM t_user WHERE user_name = '%s') = 1" +
//                " THEN code ~ (SELECT organization FROM t_user WHERE user_name = '%s')" +
                " THEN code  ILIKE regexp_replace(concat('%%',(SELECT organization FROM t_user WHERE user_name = '%s'),'%%'),'\\\\','\\\\\\','g') " +
                " ELSE 1 = 2 END)) as %s",
                userName,userName,userName,userName,userName,userName,tmpTableName);

        String sql;
        if (!StringUtils.hasLength(userName)) {
            sql = joinKey.concat(" (SELECT agentid FROM dev) as " + tmpTableName);
        } else {
            sql = joinKey.concat(joinSql);
        }

        return sql;
    }

    public String createJoinSql(String tmpTableName) {
        String userName = TokenUtil.getCurrentUserName();
        return createJoinSqlByUserName(userName,tmpTableName);
    }
}
